package com.student91.recruit.util.servlet;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 这是一个有关servlet的工具集合：包含request和response
 * 2017年7月19日 09点53分
 * <p>
 * 951755883@qq.com
 */
public class ServletUtil {

    //获取客户端ip
    public static String getRemoteAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (hasIp(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (hasIp(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (hasIp(ip)) {
            ip = request.getRemoteAddr();
        }
        //本地ip转真实ip
        if (isLocalIp(ip)) {
            ip = localIp2RealIp(ip);
        }
        return ip;
    }

    //字符串是否含有ip 该方法服务于 ServletUtil.getRemoteAddress
    private static boolean hasIp(String ip) {
        return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip);
    }

    //判断是否是本地ip
    public static boolean isLocalIp(String ipString) {
        return "0:0:0:0:0:0:0:1".equals(ipString) || "127.0.0.1".equals(ipString) || "0:0:0:0:0:0:0:1%0".equals(ipString);
    }


    /**
     * 检查以localhost,127.0.0.1访问时得到真实IP
     *
     * @param localhostIp
     * @return
     */
    public static String localIp2RealIp(String localhostIp) {
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            localhostIp = inetAddress.getHostAddress();//获取本地ip
            if (localhostIp != null && localhostIp.length() > 15) {
                if (localhostIp.indexOf(",") > 0) {
                    localhostIp = localhostIp.substring(0, localhostIp.indexOf(","));
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return localhostIp;
    }

}

